package cn.hwadee.muying.commons.utils.spring.converter;

import org.apache.commons.beanutils.converters.AbstractConverter;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @描述: 时间戳转换器
 * @作者: Pengo.Wen
 * @日期: 2017-07-06 11:38
 * @版本: v1.0
 */
public class TimestampConverter extends AbstractConverter {

    private static final List<String> formarts = new ArrayList<>(4);
    static{
        formarts.add("yyyy-MM");
        formarts.add("yyyy-MM-dd");
        formarts.add("yyyy-MM-dd HH:mm");
        formarts.add("yyyy-MM-dd HH:mm:ss");
    }

    @Override
    protected Object convertToType(Class type, Object value) throws Throwable {
        if(value != null) {
            if (value instanceof String) {
                String source = ((String) value).trim();
                return StringToTimeConverter.convert(source);
            }
        }
        return null;
    }

    @Override
    protected Class getDefaultType() {
        return Timestamp.class;
    }

    @Override
    protected String convertToString(Object value) throws Throwable {
        SimpleDateFormat sdf = new SimpleDateFormat();

        for (int i = 0; i < formarts.size(); i++) {
            try {
                sdf.applyPattern(formarts.get(i));
                return sdf.format(value);
            }catch (Exception ex){

            }
        }

        return super.convertToString(value);
    }
}
